<template>
  <div class="page-container">
    <div class="salary-card-distribute-card">
      <div class="distribute-card-head">{{ welfareName }}发放流程：</div>
      <div class="distribute-card-cont">
        <div class="distribute-step-box">
          <div class="img-box">
            <img src="@/assets/img/careCard/distribute/1.png" alt="" />
            <p class="img-bottom">提交发放清单</p>
          </div>
          <div class="split-icon">
            <i class="fa fa-angle-double-right"></i>
          </div>
          <div class="img-box">
            <img src="@/assets/img/careCard/distribute/2.png" alt="" />
            <p class="img-bottom">二次确认发放</p>
          </div>
          <div class="split-icon">
            <i class="fa fa-angle-double-right"></i>
          </div>
          <div class="img-box">
            <img src="@/assets/img/careCard/distribute/3.png" alt="" />
            <p class="img-bottom">员工自动到账</p>
          </div>
          <div class="split-icon">
            <i class="fa fa-angle-double-right"></i>
          </div>
          <div class="img-box">
            <img src="@/assets/img/careCard/distribute/4.png" alt="" />
            <p class="img-bottom">员工消费</p>
          </div>
          <div class="split-icon">
            <i class="fa fa-angle-double-right"></i>
          </div>
          <div class="img-box">
            <img src="@/assets/img/careCard/distribute/5.png" alt="" />
            <p class="img-bottom">
              月结充值回款
              <br />
              消费多少结多少
            </p>
          </div>
        </div>
      </div>
    </div>
    <div class="salary-card-distribute-card">
      <div class="distribute-page-center">
        <el-row>
          <el-col :span="6">
            <div class="distribute-allocation">
              <div class="distribute-allocation-title">{{ welfareName }}可分配额度(元)</div>
              <div class="distribute-allocation-money">{{ effectiveAmount }}</div>
              <div class="distribute-allocation-cont">
                <el-button type="primary" @click="onAllocationBtnClick">批量分配</el-button>
              </div>
            </div>
          </el-col>
          <el-col :span="18">
            <div class="distribute-form-wrapper">
              <el-form ref="form" label-width="240px" :model="form" :rules="rules">
                <el-form-item label="分配主题：" class="distribute-form-item" prop="grantTheme">
                  <el-input
                    v-model="form.grantTheme"
                    class="distribute-form-item-input"
                    :maxlength="20"
                  ></el-input>
                </el-form-item>
                <el-form-item label="每位员工分配额度(元)：" prop="amount" :maxlength="11">
                  <el-input
                    v-model.trim="form.amount"
                    class="distribute-form-item-input"
                  ></el-input>
                </el-form-item>
                <el-form-item label="可分配(人)：">
                  <span>{{ peopleNum }}</span>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="distribute-line">
      <div v-if="!!total" class="distribute-line-left">
        <span>已选择(人)：</span>
        <span class="people-num">{{ total }}</span>
      </div>
      <div class="distribute-line-right">
        <el-button v-if="!!total" type="primary" @click="delAllUser">清空全部人员</el-button>
        <el-button type="primary" @click="onSelectUsersBtnClick">选择企业人员</el-button>
      </div>
    </div>
    <div v-if="!!total" class="salary-card-distribute-card">
      <wf-el-table
        height="100%"
        :list="list"
        :total="total"
        :current="current"
        @on-page-change="onPageChange"
      >
        <el-table-column prop="realName" label="姓名"></el-table-column>
        <el-table-column prop="deptName" label="部门"></el-table-column>
        <el-table-column prop="mobilePhone" label="账号"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="delUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </wf-el-table>
    </div>
    <div v-if="!!total" class="distribute-footer">
      <el-button type="primary" :loading="loading" @click="onSubmit">提交并发放清单</el-button>
    </div>
    <import-allocation ref="importAllocation" />
    <select-users ref="selectUsers" @on-ok="onSelectedUsers" />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex';
  import { isMoney } from '@/utils/regExpUtil';
  import { getLocalData } from '@/utils/localStore';

  import WfElTable from '@/components/Table/index';
  import ImportAllocation from './drawer/ImportAllocation';
  import SelectUsers from './modal/SelectUsers';

  import { getAccountDetail, submitAllocate, getAllUserByIds } from '@/api/careCard';

  export default {
    components: {
      WfElTable,
      ImportAllocation,
      SelectUsers,
    },
    data() {
      const validateAmount = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入分配额度'));
          return;
        }
        if (!isMoney(value)) {
          callback(new Error('必须大于0，且限制最大输入99999999.99'));
          return;
        }
        const _val = parseInt(value);
        if (!_val || _val > 99999999.99) {
          callback(new Error('必须大于0，且限制最大输入99999999.99'));
          return;
        }
        callback();
      };
      return {
        form: {
          amount: 100,
          grantTheme: '',
        },
        rules: {
          grantTheme: [{ required: true, message: '请输入分配主题', trigger: 'change' }],
          amount: [{ required: true, validator: validateAmount, trigger: 'change' }],
        },
        current: 1,
        effectiveAmount: 0,
        originList: [],
        loading: false,
      };
    },
    computed: {
      ...mapGetters('user', ['userInfo']),
      organizationId() {
        return this.userInfo.organId;
      },
      peopleNum() {
        const amount = parseFloat(this.form.amount);
        return amount > 0 ? Math.floor(this.effectiveAmount / amount) : 0;
      },
      total() {
        return this.originList.length || 0;
      },
      list() {
        const index = (this.current - 1) * 10;
        if (!this.originList.length) {
          return [];
        }
        return this.originList.slice(index, index + 10);
      },
      welfareName() {
        return getLocalData('welfareName') || '';
      },
    },
    // mounted() {
    //   this.initData();
    // },
    activated() {
      this.initData();
    },
    methods: {
      async initData() {
        this.originList = [];
        const { data } = await getAccountDetail();
        const query = this.$route.query || {};
        if (query.ids && query.ids.length) {
          const ids = query.ids.split(',');
          const { data } = await getAllUserByIds({ organizationId: this.organizationId, ids });
          this.originList = Array.isArray(data)
            ? data.map(item => ({
                id: item.id,
                userId: item.id,
                realName: item.realName,
                mobilePhone: item.phone,
                deptName: item.organName,
              }))
            : [];
        }
        this.effectiveAmount = data && data.effectiveAmount ? data.effectiveAmount : 0;
      },
      onAllocationBtnClick() {
        this.$refs['importAllocation'].open(this.organizationId);
      },
      onSelectUsersBtnClick() {
        this.$refs['selectUsers'].show(this.organizationId);
      },
      onPageChange(data) {
        this.current = data.current;
      },
      onSelectedUsers(list) {
        if (list.length > 0) {
          const originIds = this.originList.map(item => item.id);
          this.originList = list.reduce((col, item) => {
            originIds.includes(item.id) ? null : col.push({ ...item });
            return col;
          }, this.originList);
        }
      },
      async onSubmit() {
        this.$refs['form'].validate(async valid => {
          if (valid) {
            if (this.peopleNum < this.originList.length) {
              this.$message.error(
                `余额不足，选择人数（${this.originList.length}人）大于可分配人数（${this.peopleNum}人）`
              );
              return false;
            }
            this.loading = true;
            await submitAllocate({
              ...this.form,
              organizationId: this.organizationId,
              userAllocateList: this.originList.map(item => ({ userId: item.userId, number: 1 })),
            });
            this.loading = false;
            this.$router.replace('/careCard/distributeList');
          }
        });
      },
      delUser(row) {
        this.originList = this.originList.filter(item => item.id !== row.id);
      },
      delAllUser() {
        this.originList = [];
      },
    },
  };
</script>

<style lang="scss" scoped>
  .salary-card-distribute-card {
    border-radius: 5px;
    padding: 10px;
    background: #ffffff;
    color: #7f848b;
    margin-bottom: 15px;
    font-size: 14px;
  }
  .distribute-card-head {
    color: #7f848b;
    padding: 10px;
  }
  .distribute-step-box {
    display: flex;
    justify-content: center;
    align-items: center;
    > .img-box {
      width: 160px;
      text-align: center;
      .img-bottom {
        color: #353739;
      }
    }
    > .split-icon {
      font-size: 37px;
      color: #cfcfcf;
      padding: 0 20px;
    }
  }
  .distribute-page-center {
    height: 280px;
  }
  .distribute-allocation {
    height: 220px;
    text-align: center;
    border-right: 1px solid #efeff0;
    padding: 40px 0;
  }
  .distribute-allocation-title {
    margin: 5px 0;
  }
  .distribute-allocation-money {
    color: #697bff;
    font-size: 28px;
    margin: 5px 0;
  }
  .distribute-allocation-cont {
    margin-top: 30px;
  }
  .distribute-form-wrapper {
    padding: 40px 50px 40px 0;
  }
  .distribute-form-item-input {
    max-width: 400px;
  }
  .distribute-form-item-tip {
    display: block;
    height: 30px;
  }
  .distribute-line {
    vertical-align: middle;
    width: 100%;
    margin-bottom: 15px;
  }
  .distribute-line-left {
    float: left;
    .people-num {
      color: #1e2023;
      font-size: 26px;
    }
  }
  .distribute-line-right {
    margin-left: 250px;
    text-align: right;
  }
  .distribute-footer {
    padding: 15px 0;
    text-align: right;
  }
</style>
